from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from redis import StrictRedis
from flask_wtf.csrf import CSRFProtect
from flask_session import Session
from config import config_dict

import logging
from logging.handlers import RotatingFileHandler




db = SQLAlchemy()
redis_store = None

def setup_log(config_name):
    logging.basicConfig(level=logging.DEBUG)
    logging.basicConfig(level=config_dict[config_name].LOG_LEVEL)
    file_log_handler = RotatingFileHandler("logs/log", maxBytes=1024 * 1024 * 100, backupCount=10)
    formatter = logging.Formatter('%(levelname)s %(filename)s:%(lineno)d %(message)s')
    file_log_handler.setFormatter(formatter)
    logging.getLogger().addHandler(file_log_handler)


def create_app(config_name):
    app = Flask(__name__)
    setup_log(config_name)
    app.config.from_object(config_dict[config_name])
    db.init_app(app)
    global redis_store
    redis_store = StrictRedis(host=config_dict[config_name].REDIS_HOST, port=config_dict[config_name].REDIS_PORT, db=config_dict[config_name].REDIS_NUM)
    CSRFProtect(app)
    Session(app)
    from info.modules.index import index_blu
    app.register_blueprint(index_blu)
    from info.modules.passport import passport_blu
    app.register_blueprint(passport_blu)

    return app




